package util

import (
	"archive/zip"
	"fileNest/storage"
	"fmt"
	"io"
	"net/url"
	"reflect"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
)

// value转为BsonM格式
func ValueToBsonM(value interface{}, stripEmpty bool) (result bson.M, err error) {
	val := reflect.TypeOf(value)
	if val == nil || val.Kind() != reflect.Struct {
		err = fmt.Errorf("传入值非结构体")
		return
	}

	temp, err := bson.Marshal(value)
	if err != nil {
		return
	}
	if err = bson.Unmarshal(temp, &result); err != nil {
		return
	}

	if stripEmpty {
		for k, v := range result {
			if v == nil || reflect.ValueOf(v).IsZero() {
				delete(result, k)
			}
		}
	}
	return
}

func DownloadZipHandler(ctx *gin.Context, fileName string, files []storage.DownloadObjectType) {
	// 设置响应头，让浏览器下载
	ctx.Writer.Header().Set("Content-Type", "application/zip")
	ctx.Writer.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+url.PathEscape(fileName)+".zip")

	zipWriter := zip.NewWriter(ctx.Writer)
	defer zipWriter.Close()
	for _, v := range files {
		newFile, _ := zipWriter.Create(v.Name)
		io.Copy(newFile, v.Object)
		v.Object.Close()
	}
}
